<?php
/**
 * Here is your custom functions.
 */

if (!function_exists('array_group_by')) {
    /**
     * 对二维数组进行分组
     * @param $arr
     * @param $key
     * @return array
     */
    function array_group_by($arr, $key)
    {
        $grouped = [];
        foreach ($arr as $value) {
            $grouped[$value[$key]][] = $value;
        }

        if (func_num_args() > 2) {
            $args = func_get_args();
            foreach ($grouped as $key => $value) {
                $param = array_merge([$value], array_slice($args, 2, func_num_args()));
                $grouped[$key] = call_user_func_array('array_group_by', $param);
            }
        }
        return $grouped;
    }
}

if (!function_exists('array_sort_by')) {
    /**
     * 数组排序
     * @param $arr
     * @param $key
     * @param string $type
     * @param bool $showKey
     * @return array
     */
    function array_sort_by($arr, $key, $type = 'asc', $showKey = true)
    {
        $keyValue = [];
        foreach ($arr as $k => $value) {
            $keyValue[$k] = $value[$key];
        }
        if ($type == 'asc') {
            asort($keyValue);
        } else {
            arsort($keyValue);
        }
        reset($keyValue);

        $sortData = [];
        foreach ($keyValue as $k => $value) {
            if ($showKey) {
                $sortData[$k] = $arr[$k];
            } else {
                $sortData[] = $arr[$k];
            }
        }
        return $sortData;
    }
}

if (!function_exists('camelize')) {
    /**
     *  下划线转驼峰
     * 思路:
     * step1.原字符串转小写,原字符串中的分隔符用空格替换,在字符串开头加上分隔符
     * step2.将字符串中每个单词的首字母转换为大写,再去空格,去字符串首部附加的分隔符.
     * @param $unCamelizeWords
     * @param string $separator
     * @return string
     */
    function camelize($unCamelizeWords, $separator = '_')
    {
        $unCamelizeWords = $separator . str_replace($separator, " ", strtolower($unCamelizeWords));
        return str_replace(" ", "", ucwords(ltrim($unCamelizeWords, $separator)));
    }
}

if (!function_exists('to_under_score')) {
    /**
     * 驼峰命名转下划线命名
     * @param $str
     * @return string
     */
    function to_under_score($str)
    {
        $dstr = preg_replace_callback('/([A-Z]+)/', function ($matchs) {
            return '_' . strtolower($matchs[0]);
        }, $str);
        return trim(preg_replace('/_{2,}/', '_', $dstr), '_');
    }
}

if (!function_exists('format_exception_info')) {
    /**
     * 获得随机字符串
     * @param $length
     * @return int
     * @throws Exception
     */
    function format_exception_info($e)
    {
        return sprintf("%s:%d  %s\r\n%s", $e->getFile(), $e->getLine(), $e->getMessage(), $e->getTraceAsString());
    }
}